"""
该脚本添加各自常用的弹窗小组件
"""
import os
import sys
import requests
from PySide2.QtCore import *
from PySide2.QtGui import *
from PySide2.QtWidgets import *
from ..utils.styles import STYLES
# from Widgets.calendarWindow import Calendar


class AddWidget(QWidget):
    add_Signal = Signal(str)
    def __init__(self,title,name,doc='') -> None:
        super(AddWidget,self).__init__()
        self.setStyleSheet(STYLES.COLOR_STYLES)
        self.setWindowTitle(title)
        self.setFixedWidth(335)
        self.setMaximumHeight(100)
        self.main_layout = QVBoxLayout()
        self.content_layout = QHBoxLayout()
        self.content_layout.setSpacing(15)
        self.main_label = QLabel(name)
        self.main_edit = QLineEdit()
        self.main_btn = QPushButton('确认')
        # self.main_btn.setShortcut(QKeySequence('Return'))
        self.main_btn.setShortcut('Return')
        # self.main_btn.setShortcut(Qt.Key_Enter | Qt.Key_Return)
        self.main_btn.clicked.connect(self._OK)
        self.main_btn.setStyleSheet(STYLES.BTN_STYLE_M)
        self.doc_label = QLabel(doc) #
        self.content_layout.addWidget(self.main_label)
        self.content_layout.addWidget(self.main_edit)
        self.content_layout.addWidget(self.main_btn)
        self.main_layout.addLayout(self.content_layout)
        self.main_layout.addWidget(self.doc_label)
        self.setLayout(self.main_layout)


    def _OK(self):
        text = self.main_edit.text()
        if text:
            self.add_Signal.emit(text)
            self.close()

class FieldWidget(QWidget):
    """
    返回： {'name':text,'type':_type}
    """
    field_Signal = Signal(dict)
    def __init__(self,title='',data={}):
        super(FieldWidget,self).__init__()
        self.setStyleSheet(STYLES.COLOR_STYLES)
        # self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.setWindowTitle(title)
        self.setFixedWidth(335)
        self.setMaximumHeight(100)
        self.main_layout = QVBoxLayout()
        self.content_layout = QHBoxLayout()
        self.content_layout.setSpacing(15)
        self.main_label = QLabel('字段名称:')
        self.main_edit = QLineEdit()
        self.type_comb = QComboBox()
        self.init_type()
        self.main_btn = QPushButton('确认')
        self.main_btn.setShortcut('Return')
        self.main_btn.clicked.connect(self._OK)
        self.main_btn.setStyleSheet(STYLES.BTN_STYLE_M)
        self.doc_label = QLabel('注意:为方便选择数值也归属文本类型 \n密码类型让内容显示为***')
        self.doc_label.setContentsMargins(0,15,0,8)
        self.content_layout.addWidget(self.main_label)
        self.content_layout.addWidget(self.main_edit)
        self.content_layout.addWidget(self.type_comb)
        self.content_layout.addWidget(self.main_btn)
        self.main_layout.addLayout(self.content_layout)
        self.main_layout.addWidget(self.doc_label)
        self.setLayout(self.main_layout)
        self.init_data(data)

    def init_type(self):
        type_list = ['文本','日期','状态','链接','图片','文件','视频']
        self.type_comb.addItems(type_list)

    def init_data(self,data):
        if data:
            self.main_edit.setText(data['name'])
            self.type_comb.setCurrentText(data['type'])

    def _OK(self):
        text = self.main_edit.text()
        if text:
            _type = self.type_comb.currentText()
            data = {'name':text,'type':_type}
            self.field_Signal.emit(data)
            self.close()


class LevelWidget(QWidget):
    """
    人员权限组件
    """
    level_Signal = Signal(int)
    def __init__(self,pipeline,level):
        super(LevelWidget,self).__init__()
        self.pipeline = pipeline
        self.level_list = ['基础权限','排期权限','所有权限']
        self.main_layout = QHBoxLayout()
        self.main_layout.setAlignment(Qt.AlignLeft)
        self.main_layout.setSpacing(25)
        self.name_level = QLabel(pipeline)
        self.name_level.setFixedWidth(150)
        self.level_comp = QComboBox()
        self.init_comp(level)
        self.level_comp.currentIndexChanged.connect(self._change)
        self.main_layout.addWidget(self.name_level)
        self.main_layout.addWidget(self.level_comp)
        self.setLayout(self.main_layout)



    def init_comp(self,level):
        self.level_comp.addItems(self.level_list)
        self.level_comp.setCurrentIndex(level)

    def get_level_map(self):
        """
        获取该权限信息
        """
        return {self.pipeline:self.level_comp.currentIndex()}
    
    def _change(self,index):
        self.level_Signal.emit(index)


class SearchWidget(QWidget):
    """
    查询组件，用来过滤列表，比较常用，所有通用
    """
    text_eidted_Signal = Signal(str)
    filter_Signal = Signal(str)
    def __init__(self):
        super(SearchWidget, self).__init__()
        self.search_layout = QHBoxLayout()
        self.search_edit = QLineEdit()
        self.search_edit.textEdited.connect(self._text_edited)
        self.search_btn = QPushButton('查询')
        self.search_btn.setStyleSheet(STYLES.BTN_STYLE_M)
        self.search_btn.setShortcut(QKeySequence('Return'))
        self.search_btn.clicked.connect(self._filter_username)
        self.search_layout.addWidget(self.search_edit)
        self.search_layout.addWidget(self.search_btn)
        self.setLayout(self.search_layout)

    def _text_edited(self,text):
        self.text_eidted_Signal.emit(text)

    def _filter_username(self):
        text = self.search_edit.text()
        # self.worker_list.filter_item(text)
        self.filter_Signal.emit(text)


class ColorChoose(QWidget):
    """
    获取颜色，并命名
    """
    color_Signal  = Signal(dict)
    def __init__(self):
        super(ColorChoose,self).__init__()
        self.color = '#000000'
        self.setStyleSheet(STYLES.COLOR_STYLES)
        self.setWindowTitle('选择颜色')
        self.main_layout = QHBoxLayout()
        self.name_label = QLabel('名称:')
        self.name_edit = QLineEdit()
        self.color_label = QLabel('')
        self.color_label.setStyleSheet(f'background-color:{self.color}')
        self.color_label.setFixedSize(QSize(20,20))
        self.color_btn = QPushButton('选择颜色')
        self.color_btn.setStyleSheet(STYLES.BTN_STYLE_M)
        self.color_btn.clicked.connect(self._open_color_win)
        self.ok_btn = QPushButton('确认')
        self.ok_btn.setShortcut(QKeySequence('Return'))
        self.ok_btn.setStyleSheet(STYLES.BTN_STYLE_M)
        self.ok_btn.clicked.connect(self._choose_color)
        self.main_layout.addWidget(self.name_label)
        self.main_layout.addWidget(self.name_edit)
        self.main_layout.addWidget(self.color_label)
        self.main_layout.addWidget(self.color_btn)
        self.main_layout.addWidget(self.ok_btn)
        self.setLayout(self.main_layout)
        

    def _open_color_win(self):
        self.color_win = QColorDialog.getColor()
        self.color = self.color_win.name()
        self.color_label.setStyleSheet(f'background-color:{self.color}')

    def _choose_color(self):
        name = self.name_edit.text()
        if name:
            # print(name,self.color)
            self.color_Signal.emit({name:self.color})
            self.close()
        else:
            QMessageBox.information(None,'提示','请命名')

class PathWidget(QWidget):
    """
    文件展示，快速打开窗口
    """
    def __init__(self,path):
        super(PathWidget, self).__init__()
        self.path = path
        self.main_layout = QVBoxLayout()
        self.setStyleSheet(STYLES.COLOR_STYLES)
        self.setWindowTitle('路径')
        self.setFixedWidth(335)
        self.setMaximumHeight(300)
        self.main_btn = QPushButton(path)
        self.main_btn.clicked.connect(self._show_path)
        self.main_btn.setStyleSheet(STYLES.BTN_STYLE_M)
        self.main_layout.addWidget(self.main_btn)
        self.setLayout(self.main_layout)

    def _show_path(self):
        try:
            os.startfile(self.path.replace('\\', '/'))
        except Exception as _show_path_ERR:
            print('_show_path_ERR:',_show_path_ERR)
        finally:
            self.close()

class InforWidget(QWidget):
    """
    信息组件，用在任务信息框中
    """
    color_Signal  = Signal(dict)
    def __init__(self,username,ctime,ctype,content):
        super(InforWidget,self).__init__()
        self.content = content
        self.setMinimumWidth(320)
        self.main_layout = QVBoxLayout()
        self.main_layout.setAlignment(Qt.AlignTop)
        self.user_layout = QHBoxLayout()
        self.username_label = QLabel(username)
        self.username_label.setAlignment(Qt.AlignLeft)
        self.username_label.setFixedHeight(20)
        self.time_label = QLabel(ctime)
        self.time_label.setAlignment(Qt.AlignRight)
        self.user_layout.addWidget(self.username_label)
        self.user_layout.addWidget(self.time_label)
        self.main_layout.addLayout(self.user_layout)
        self.init_content(ctype,content)
        

        # self.main_layout.addWidget(self.content_label)
        self.setLayout(self.main_layout)


    def init_content(self,ctype,content):
        """
        初始化内容，
        类似微信对话框
        一行信息包括两个组件，如果是文本信息，则有网络提示组件，与文本内容label
        网络提示组件都在右边与微信相反。
        如果是img,则由img与网络提示图标构成
        """
        content_layout = QHBoxLayout()
        content_layout.setAlignment(Qt.AlignTop)
        tip_label = QLabel('')
        tip_label.setFixedWidth(20)
        if ctype == 'img':
            
            content_widget = QToolButton()
            content_widget.setStyleSheet(STYLES.TOOLBTN_FLAT)
            content_widget.clicked.connect(self._showimg)
            try:
                res = requests.get(content)
                qimg = QImage.fromData(res.content)

                # newimg = qimg.scaledToWidth(r_img_w)
                # newimg = newimg.scaledToHeight(r_img_h)
            except:
                qimg = QImage(STYLES.XIMG_PATH)
                tip_label.setText('!')

            img_w = qimg.width()
            img_h = qimg.height()
            r_img_h = 100
            r_img_w = 100*img_w/img_h
            pix = QPixmap.fromImage(qimg)
            content_widget.setIcon(QIcon(pix))
            content_widget.setIconSize(QSize(r_img_h,r_img_w))

        elif ctype == 'local_img':
            content_widget = QToolButton()
            content_widget.setStyleSheet(STYLES.TOOLBTN_FLAT)
            content_widget.clicked.connect(self._showimg)
            qimg = QImage(content)
            img_w = qimg.width()
            img_h = qimg.height()
            r_img_h = 100
            r_img_w = 100*img_w/img_h
            # newimg = qimg.scaledToWidth(r_img_w)
            # newimg = newimg.scaledToHeight(r_img_h)
            # print('变了吗？')
            pix = QPixmap.fromImage(qimg)
            content_widget.setIcon(QIcon(pix))
            content_widget.setIconSize(QSize(r_img_h,r_img_w))

        else:
            content_widget = QLabel(content)
            content_widget.setTextInteractionFlags(Qt.TextSelectableByMouse)
        
        content_layout.addWidget(content_widget)
        content_layout.addWidget(tip_label)
        self.main_layout.addLayout(content_layout)


    def _showimg(self):
        os.startfile(self.content)

class InputWidget(QWidget):
    input_Signal = Signal(str)
    def __init__(self,text=''):
        super(InputWidget,self).__init__()
        self.setStyleSheet(STYLES.COLOR_STYLES)
        self.setWindowTitle('输入')
        self.setFixedWidth(335)
        self.setMaximumHeight(100)
        self.main_layout = QHBoxLayout()
        self.input_edit = QLineEdit()
        self.input_edit.setText(text)
        self.main_btn = QPushButton('OK')
        self.main_btn.setStyleSheet(STYLES.BTN_STYLE_M)
        self.main_btn.clicked.connect(self._OK)
        self.main_btn.setShortcut('Return')
        self.main_layout.addWidget(self.input_edit)
        self.main_layout.addWidget(self.main_btn)
        self.setLayout(self.main_layout)

    def _OK(self):
        text = self.input_edit.text()
        self.input_Signal.emit(text)
        self.close()


class StatusWidget(QWidget):
    changed_Signal = Signal(str)
    def __init__(self,status,task_status):
        super(StatusWidget, self).__init__()
        self.task_status = task_status
        self._value = status
        # self.setMinimumSize(QSize(80,50))
        self.main_layout = QHBoxLayout()
        self.main_layout.setAlignment(Qt.AlignCenter)
        self.main_layout.setSpacing(0)
        self.comb = QComboBox()
        self.comb.setMinimumSize(QSize(80,20))
        self.comb.setView(QListView())
        self.comb.setStyleSheet(STYLES.COMB_12)
        self.color_label = QLabel('')
        self.color_label.setFixedSize(QSize(20,20))
        self.color_label.setAlignment(Qt.AlignCenter)
        # self.color_label.setContentsMargins(0,0,0,0)
        self.main_layout.addWidget(self.comb)
        self.main_layout.addWidget(self.color_label)

        self.setLayout(self.main_layout)
        self.init_status(status,task_status)
        self.comb.currentTextChanged.connect(self._changed)

    def init_status(self,status,task_status):
        self.comb.clear()
        if status:
            color = task_status[status]
            self.comb.addItems(list(task_status.keys()))
            self.comb.setCurrentText(status)
            self.color_label.setStyleSheet(f'background-color:{color}')
            # for s,color in task_status.items():
            #     self.comb.addItem(s)
                
    def _changed(self,status):
        color = self.task_status[status]
        self._value = status
        self.color_label.setStyleSheet(f'background-color:{color}')
        self.changed_Signal.emit(status)



class TypeItemWidget(QWidget):
    """
    根据不同的传入类型标识生成不同的类型组件,用来显示在Table中。
    有QTableWidget与QTreeWidget两种，所以需要对应QTableWidgetItem和QTreeWidgetItem
    /文本 ： 包括一些数值以及带秒格式的日期
    /密码 ： 以*号显示
    /日期 ： 仅2021-12-13这类日期，不带时分秒，可以直接选择日期
    /状态 ： 呈现任务状态
    /链接 ： 点击跳转链接
    /图片 ： 可以上传图片，可以展示图片
    /文件 ： 可以上传文件，可以下载文件，有大小与类型限制
    /视频 ： 可以上传视频,可以观看视频，有大小与类型限制
    """
    _update_Signal = Signal(int)
    def __init__(self,_type,_value,_status):
        super(TypeItemWidget, self).__init__()
        self._type = _type
        self._value = _value
        self._status = _status
        self.current_widget = None
        self.main_layout = QVBoxLayout()
        self.init_widget(_type,_value)
        self.setLayout(self.main_layout)

        

    def init_widget(self,_type,_value):

        if _type == '文本':
            widget = QPushButton(_value)
            widget.setStyleSheet(STYLES.BTN_FLAT_GREY_12)
            # widget.setMinimumSize(QSize(100,100))
            widget.clicked.connect(self._input_text)
        elif _type == '密码':
            widget = QPushButton('****')
            widget.setStyleSheet(STYLES.BTN_FLAT_GREY_12)
            widget.clicked.connect(self._input_password)
        elif _type == '日期':
            widget = QPushButton(_value.replace(' 00:00:00',''))
            widget.setStyleSheet(STYLES.BTN_FLAT_GREY_12)
            widget.clicked.connect(self._input_date)
        elif _type == '状态':
            start_status = '未开始' if not _value else _value
            widget = StatusWidget(start_status,self._status)
            widget.changed_Signal.connect(self._change)
        elif _type == '链接':
            widget = QPushButton(_value)
            widget.setStyleSheet(STYLES.BTN_FLAT_GREY_12)
            widget.clicked.connect(self._input_text)
        elif _type == '图片':
            widget = QToolButton()
            widget.setStyleSheet(STYLES.TOOLBTN_FLAT_12)
            widget.setIcon(QIcon(os.path.join(_value.replace('img:',''))))
            widget.setIconSize(QSize(50, 50))
            widget.clicked.connect(self._input_img)
        elif _type == '文件':
            widget = QToolButton()
            widget.setStyleSheet(STYLES.TOOLBTN_FLAT_12)
            if _value:
                widget.setIcon(QIcon(STYLES.FILE_PATH))
                widget.setIconSize(QSize(50, 50))
            widget.clicked.connect(self._input_asset)
        elif _type == '视频':
            widget = QToolButton()
            
            widget.setIcon(QIcon(STYLES.VIDEO_PATH))
            widget.clicked.connect(self._input_video)
        self.main_layout.addWidget(widget)


    def _input_text(self):
        self.current_widget = self.sender()
        self.iw = InputWidget(self.current_widget.text())
        self.iw.input_Signal.connect(self._set_btn_text)
        self.iw.show()

    def _set_btn_text(self,value):
        self.current_widget.setText(value)
        self._value = value
        self._update_Signal.emit(1)


    def _input_link(self):
        self.current_widget = self.sender()
        self.iw = InputWidget(self.current_widget.text())
        self.iw.input_Signal.connect(self._set_btn_link)
        self.iw.show()

    def _set_btn_link(self,value):
        self.current_widget.setText(value)
        self._value = 'link:' + value
        self._update_Signal.emit(1)



    def _input_password(self):
        self.current_widget = self.sender()
        self.iw = InputWidget(self._value)
        self.iw.input_Signal.connect(self._set_btn_password)
        self.iw.show()

    def _set_btn_password(self,value):
        self.current_widget.setText('****')
        self._value = value
        self._update_Signal.emit(1)

    def _input_date(self):
        self.current_widget = self.sender()
        self.iw = Calendar()
        self.iw.dateSignal.connect(self._set_btn_text)
        self.iw.show()

    def _change(self,value):
        self.current_widget = self.sender()
        self._value = value
        self._update_Signal.emit(1)

    def _input_img(self):
        """
        选择本地图片，至于上传到云端的图片，需要另外考虑，是否用过滤的方式来显示
        """
        self.current_widget = self.sender()
        openfile_name = QFileDialog.getOpenFileName(self,'选择图片','','图片(*.jpg ; *.png;*.jpeg)')
        if openfile_name:
            img_path = openfile_name[0]
            if os.path.exists(img_path):
                self._value = 'img:'+ img_path  
                self.current_widget.setIcon(QIcon(img_path))
                self.current_widget.setIconSize(QSize(50, 50))
            else:
                self._value = ''
        self._update_Signal.emit(1)

    def _input_asset(self):
        """
        选择本地文件，至于上传到云端的图片
        """
        self.current_widget = self.sender()
        openfile_name = QFileDialog.getOpenFileName(self,'选择文件','','(*.)')
        if openfile_name:
            file_path = openfile_name[0]
            if os.path.exists(file_path):
                self._value = 'asset:' + file_path  
            else:
                self._value = ''
        self._update_Signal.emit(1)

    def _input_video(self):
        """
        选择本地视频,
        """
        self.current_widget = self.sender()
        openfile_name = QFileDialog.getOpenFileName(self,'选择视频','','视频(*.M4V ;*.MP4 ; *.mov;)')
        if openfile_name:
            video_path = openfile_name[0]
            if os.path.exists(video_path):
              self._value = 'video:' + video_path  
            else:
                self._value = ''
        self._update_Signal.emit(1)

    def value(self):
        return self._value



class EmbeddingProgressBar(QWidget):

    def __init__(self):
        super(EmbeddingProgressBar,self).__init__()

        self.main_layout = QHBoxLayout()
        self.show_label = QLabel('')
        self.progress = QProgressBar()
        self.progress.setFixedHeight(10)
        self.main_layout.addWidget(self.show_label)
        self.main_layout.addWidget(self.progress)
        self.setLayout(self.main_layout)

    def setName(self,name):
        self.show_label.setText(name)

    def setValue(self,value):
        self.progress.setValue(value)



class IProgresBar(QWidget):
    force_close_Signal =  Signal(int)
    def __init__(self,title=''):
        super(IProgresBar, self).__init__()
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(0)
        # label_font=QFont('',12)
        self.show_label = QLabel(title)
        self.progress_layout = QHBoxLayout()
        self.progress = QProgressBar()
        self.progress.setMaximumHeight(15)
        self.percen_label = QLabel('0')
        self.percen_label.setStyleSheet(STYLES.COLOR_STYLES)
        # self.percen_label.setFont(label_font)
        self.progress_layout.addWidget(self.progress)
        self.progress_layout.addWidget(self.percen_label)
        self.main_layout.addWidget(self.show_label)
        self.main_layout.addLayout(self.progress_layout)
        self.setLayout(self.main_layout)

    def set_percent(self,percent):
        self.progress.setValue(percent)
        self.percen_label.setText(str(percent))

    def closeEvent(self, *args, **kwargs):
        print('关闭进度')
        self.force_close_Signal.emit(1)
        self.close()

class CountThread(QThread):
    """
    多线程操作并计数
    """
    def __init__(self,parent):
        super(CountThread, self).__init__()
        self.parent = parent
        # self.discopys = parent.discopys

    def run(self):
        pass


class InfoListWidget(QWidget):
    """
    信息列表创建
    """
    def __init__(self,title,doc=''):
        super(InfoListWidget, self).__init__()
        self.setStyleSheet(STYLES.COLOR_STYLES)
        self.setWindowTitle(title)
        self.main_layout = QVBoxLayout()
        self.main_label = QLabel(doc)
        self.main_label.setFont(STYLES.FONT_N_12)
        self.main_label.setAlignment(Qt.AlignCenter)
        self.main_list = QListWidget()
        self.main_layout.addWidget(self.main_label)
        self.main_layout.addWidget(self.main_list)
        self.setLayout(self.main_layout)

    def setData(self,data_list):
        self.main_list.clear()
        self.main_list.addItems(data_list)